package com.zc.service.permissionService.impl;

import com.zc.dao.UsersMapper;
import com.zc.dao.permission.RoleMapper;
import com.zc.entity.Path;
import com.zc.entity.Role;
import com.zc.entity.Users;
import com.zc.initConstructor.GlobalData;
import com.zc.service.JedisClient;
import com.zc.service.permissionService.PermissionService;
import com.zc.study.pay.MD5Util;
import com.zc.utils.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Resource
    private RoleMapper roleDao;

    @Resource
    private UsersMapper userDao;

    @Resource
    private JedisClient jedis;

    /**
     * 创建角色
     *
     * @param role
     * @param permissionList
     * @param users
     * @throws Exception
     */
    @Override
    public void saveRole(Role role, String permissionList, Users users) throws Exception {
        //获取时间
        int oldId = 0;
        try {
             oldId = role.getId();
        }catch (NullPointerException e){
        }
        role.setId(null);
        String timeNow = DateUtils.getStringToday();
        role.setCreateTime(timeNow);
        role.setCreator(users.getUsername());
        role.setFatherLeaf(users.getRoleId());
        roleDao.insertSelective(role);//插入并获取自增的id
        int roleId = role.getId();

        //处理凋后面的尾部","
        if (permissionList.endsWith(",")) {
            permissionList = permissionList.substring(0, permissionList.length() - 1);
        }
        String[] strings = permissionList.split(",");

//        List<String> list = new ArrayList<>();
//        for (String s :strings){
//            list.add(s);
//        }

        Map<String, Object> params = new HashMap<>();

        params.put("roleId", roleId);
        params.put("pathId", strings);

        roleDao.insertPathRefRoleId(params);

        //更新user表关联id
        params.put("newId", roleId);
        params.put("oldId", oldId);
        userDao.updateByRoleId(params);

        //更新role表关联id
        roleDao.updateByRoleId(params);
    }


    /**
     * @param roleId
     * @return
     * @throws Exception
     */
    @Override
    public List<Role> findAllRole(String roleId) throws Exception {
        List<Role> roles = roleDao.findAllRole(roleId);
        for (Role role : roles) {
            Role ss = roleDao.selectByPrimaryKey(Integer.parseInt(role.getFatherLeaf()));
            role.setFatherLeaf(ss.getRoleName());
        }
        return roles;
    }

    @Override
    public String findAllPathByroleId(String roleId) {
        List<Path> list;
        if ("1".equals(roleId)) {
            list = userDao.selectPathAll();
        } else {
            list = userDao.selectPathByrole(roleId);
        }
        String tree = "";
        Map<Integer, StringBuffer> treeMap = new LinkedHashMap<>();
        //初始化map,拼接根目录
        initNavMap(treeMap, list);
        //拼接sonleaf
        splitSonleaf(treeMap, list);
        //最后做完整拼接
        tree = splitComplete(treeMap);
        return tree;
    }

    @Override
    public Map<String, Object> findRoleDetail(Integer roleId) throws Exception {
        //查询角色的相关信息
        Role role = roleDao.selectByPrimaryKey(roleId);
        //查询该角色能访问的path路径
        List<Path> paths = userDao.selectPathByrole(roleId + "");
        List<Integer> list = new ArrayList<>();
        for (Path pp : paths) {
            list.add(pp.getId());
        }
        //将相关信息封装到map中
        Map<String, Object> map = new HashMap<>();
//        //获取父类角色pathTree.
//        String fatherTree = jedis.get(confirmMID);
        map.put("role", role);
        map.put("list", list);
//        map.put("fatherTree",fatherTree);
        return map;

    }

    @Override
    public void deleteRoleById(Integer roleId) throws Exception {
        Role role = roleDao.selectByPrimaryKey(roleId);
        String deleter = role.getCreator();
        role.setDeleter(deleter);
        String timeNow = DateUtils.getStringToday();
        role.setDeleteTime(timeNow);
        role.setState(1);
        //根据id改变角色state,假删
        roleDao.updateByPrimaryKeySelective(role);
        //同时删除pathRefroleID相关信息(真删)
        userDao.deleteByRoleId(roleId);
        boolean flag = true;
        //初始化集合
        List<Role> list = roleDao.findAllRole(roleId+"");
        List<Role> list2 = new ArrayList<>();
        while (flag) {
            if (list != null) {
                //查出子级角色
                for (Role role1 : list) {
                    int roleId2 = role1.getId();
                    role1.setDeleteTime(timeNow);
                    role1.setDeleter(deleter);
                    role1.setState(1);
                    roleDao.updateByPrimaryKeySelective(role1);
                    List<Role> zz = roleDao.findAllRole(roleId2+"");
                    for (Role aa : zz) {
                        list2.add(aa);
                    }
                }
                list = null;
            }
            else if(list2 != null){
                //查出子级角色
                for (Role role1 : list2) {
                    int roleId2 = role1.getId();
                    role1.setDeleteTime(timeNow);
                    role1.setDeleter(deleter);
                    role1.setState(1);
                    roleDao.updateByPrimaryKeySelective(role1);
                    List<Role> zz = roleDao.findAllRole(roleId2+"");
                    for (Role aa : zz) {
                        list.add(aa);
                    }
                }
                list2 = null;
            }else{
                flag = false;
            }
        }
    }

    @Override
    public void saveUser(Users user) throws Exception {
        String password = user.getPassword();
        user.setPassword(GlobalData.decoratePassword(password));
        userDao.insertSelective(user);
    }

    private void initNavMap(Map<Integer, StringBuffer> navMap, List<Path> list) {
        //将key:根目录和value:stringbuffer初始化map
        for (Path path : list) {
            StringBuffer sb = null;
            Integer rootID = path.getId();
            Integer rootLeaf = path.getRootLeaf();
            if (0 == rootLeaf) {
                sb = new StringBuffer();
                String content = "";
                String pathId = getpathID(path.getPathName());
                if (path.getSonLeaf() == 0) {
                    content = "&&@@<li><span><i class='icon-folder-close-alt'></i> " + path.getRemark() + "</span><input " +
                            "type='checkbox'  value='" + path.getId() + "' class='choose' onclick='chooseAll(this);'/><ul>";
                } else {
                    content = "<li><span><i class='icon-calendar'></i> " + path.getRemark() + "</span><input " +
                            "type='checkbox'  value='" + path.getId() + "' class='choose'/>";
                }
                sb.append(content);
                navMap.put(rootID, sb);
            }
        }

    }

    private void splitSonleaf(Map<Integer, StringBuffer> navMap, List<Path> list) {
        for (Path path : list) {
            //判断是不是根目录
            if (path.getRootLeaf() == 0) {
                continue;
            }
            int fatherLeaf = path.getFatherLeaf();
            String pathId = getpathID(path.getPathName());
            String content = "<li><span class='badge badge-success'><i class='icon-minus-sign'></i> " + path.getRemark() + "</span>" +
                    "<input type='checkbox'  value='" + path.getId() + "' class='choose' onclick = 'chooseFather(this);'/>";
            navMap.get(fatherLeaf).append(content);
        }
    }

    private String splitComplete(Map<Integer, StringBuffer> navMap) {
        StringBuilder sb = new StringBuilder();
        String end = "</ul></li>";
        for (Map.Entry<Integer, StringBuffer> map : navMap.entrySet()) {
            String content = map.getValue().toString();
            if (content.startsWith("&&@@")) {
                sb.append(content.replace("&&@@", "")).append(end);
            } else {
                sb.append(content);
            }
        }
        return sb.toString();
    }

    private String getpathID(String pathname) {
        //字符串类似"html/twoProduce.html";
        String pathID = "";
        try {
            int index = pathname.lastIndexOf("/");
            int lastindex = pathname.lastIndexOf(".");
            pathID = pathname.substring(index + 1, lastindex);
        } catch (StringIndexOutOfBoundsException e) {
            return pathname;
        }
        return pathID;
    }
}
